package celiasoft.itasalibtest;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import javax.net.ssl.HttpsURLConnection;

import org.apache.http.util.ByteArrayBuffer;

import android.util.Log;

public class DownloadFileFromUrl {

	public static void DownloadFromUrl(String DownloadUrl, String fileName) {

		try {
			File root = android.os.Environment.getExternalStorageDirectory();

			File dir = new File(root.getAbsolutePath());
			if (dir.exists() == false) {
				dir.mkdirs();
			}

			URL url = new URL(DownloadUrl); // you can write here any link
			File file = new File(dir, fileName);

			if (file.exists())
				file.delete();

			long startTime = System.currentTimeMillis();
			Log.d("DownloadManager", "download begining");
			Log.d("DownloadManager", "download url:" + url);
			Log.d("DownloadManager", "downloaded file name:" + fileName);
			// Log.d("DownloadManager", "downloaded file path:" +
			// file.getAbsolutePath());

			/* Open a connection to that URL. */
			HttpsURLConnection ucon = (HttpsURLConnection) url.openConnection();
			ucon.setRequestProperty("User-agent", "Mozilla/4.0");
			ucon.setInstanceFollowRedirects(false);
			/*
			 * Define InputStreams to read from the URLConnection.
			 */

			String redirUrl = ucon.getHeaderField("Location");
			InputStream is;
			if (redirUrl != null) {
				URL actualUrl = new URL(redirUrl);
				URLConnection actualConn = actualUrl.openConnection();
				is = actualConn.getInputStream();
			} else {
				is = ucon.getInputStream();
			}
			BufferedInputStream bis = new BufferedInputStream(is);

			/*
			 * Read bytes to the Buffer until there is nothing more to read(-1).
			 */
			ByteArrayBuffer baf = new ByteArrayBuffer(5000);
			int current = 0;
			while ((current = bis.read()) != -1) {
				baf.append((byte) current);
				Log.d("ehi", "data");
			}

			/* Convert the Bytes read to a String. */
			FileOutputStream fos = new FileOutputStream(file);
			fos.write(baf.toByteArray());
			fos.flush();
			fos.close();
			Log.d("DownloadManager",
					"download ready in"
							+ ((System.currentTimeMillis() - startTime) / 1000)
							+ " sec");

		} catch (IOException e) {
			Log.d("DownloadManager", "Error: " + e);
		}

	}

}
